package com.ruoyi.develop.goodsSale.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import com.ruoyi.develop.goodsOrderInner.domain.GoodsOrderInner;
import com.ruoyi.develop.goodsOrderInner.service.IGoodsOrderInnerService;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.service.impl.GoodsSaledoServiceImpl;
import com.ruoyi.develop.goodsScalaAll.service.IGoodsScalaAllService;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import com.ruoyi.system.service.ISysAreaService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 销售信息管理Controller
 * @author qh
 * @date 2023-01-05
 */
@RestController
@RequestMapping("/goodsSale/goodsSale")
public class GoodsSaleController extends BaseController {
    @Autowired
    private IGoodsSaleService goodsSaleService;
    @Autowired
    private IGoodsScalaAllService iGoodsScalaAllService;
    @Autowired
    private IGoodsOrderInService goodsOrderInService;
    @Autowired
    private ExportServiceImpl exportService;
    @Autowired
    private ISysAreaService areaService;
    @Autowired
    private GoodsSaledoServiceImpl goodsSaledoService;
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;
    @Autowired
    private IGoodsOrderInnerService goodsOrderInnerService;

    /**
     * 查询销售信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.selectList(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/listAndFour")
    public TableDataInfo listAndFour(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listAndFour(entity);
        return getDataTable(list);
    }

    @GetMapping("/listProject")
    public TableDataInfo listProject(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listProject(entity);
        return getDataTable(list);
    }
    /**
     * 查询销售信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/listLockNotZero")
    public TableDataInfo listLockNotZero(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.selectListNotZero(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/listFinishDo")
    public TableDataInfo listFinishDo(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listFinishDo(entity);
        return getDataTable(list);
    }
    /**
     * 查询销售信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/listSendNotZero")
    public TableDataInfo listSendNotZero(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listSendNotZero(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping("/listNoQishen")
    public TableDataInfo listNoQishen(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listNoQishen(entity);
        return getDataTable(list);
    }

    @GetMapping("/listBatchSale/{ids}")
    public TableDataInfo listBatchSale(@PathVariable("ids")  String ids) {
//        startPage();
//        List<GoodsSale> list = goodsSaleService.listBatch(ids);
        GoodsSale goodsSale=new GoodsSale();
        goodsSale.setProjectId(ids);
        List<GoodsSale> list = goodsSaleService.listByProjectId(goodsSale);

        return getDataTable(list);
    }

    @GetMapping("/listIds")
    public TableDataInfo listIds(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.selectList(entity);
        return getDataTable(list);
    }

    @GetMapping("/listByProOrder")
    public TableDataInfo listByProOrder(GoodsSale entity) {
        List<GoodsSale> list = goodsSaleService.listByProAndOrder(entity);
        for (GoodsSale goodsSale: list) {
            // 如果订单数量大于可用数量
            if (goodsSale.getOrderCount().compareTo(goodsSale.getRemainderCount()) >= 0) {
                goodsSale.setPleaseBuyCount(goodsSale.getOrderCount().subtract(goodsSale.getRemainderCount()));
                goodsSale.setLockCount(goodsSale.getRemainderCount());
            }else{
                goodsSale.setPleaseBuyCount(BigDecimal.ZERO);
                goodsSale.setLockCount(goodsSale.getOrderCount());
            }

        }
        return getDataTable(list);
    }

    @GetMapping("/pleaseBuyForMultiOrders")
    public TableDataInfo pleaseBuyForMultiOrders(GoodsSale entity) {
        List<GoodsSale> list = goodsSaleService.listByProAndOrder(entity);
        for (GoodsSale goodsSale: list) {
            // 如果订单数量大于可用数量
            if (goodsSale.getOrderCount().compareTo(goodsSale.getRemainderCount()) >= 0) {
                goodsSale.setPleaseBuyCount(goodsSale.getOrderCount().subtract(goodsSale.getRemainderCount()));
                goodsSale.setLockCount(goodsSale.getRemainderCount());
            }else{
                goodsSale.setPleaseBuyCount(BigDecimal.ZERO);
                goodsSale.setLockCount(goodsSale.getOrderCount());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出订单产品列表
     */
    @Log(title = "导出订单产品列表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportData")
    public void exportDetailList(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        goodsSaleService.exportData(request,response,entity);
    }


    @Log(title = "零散销售信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportSale")
    public AjaxResult exportSale(GoodsSale entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        startPage();
        List<GoodsSale> list = goodsSaleService.selectList(entity);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            // map.put("parentDept", e.getReturnDept().getParentName());
            map.put("saleDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getSaleDate()));
            map.put("invoice", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getInvoice()));
            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "零散销售记录.xlsx";
        }
        String templateName = "零散销售记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }
    @Log(title = "项目销售信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportSalePro")
    public AjaxResult exportSalePro(GoodsSale entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        startPage();
        List<GoodsSale> list = goodsSaleService.selectList(entity);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            // map.put("parentDept", e.getReturnDept().getParentName());
            map.put("saleDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getSaleDate()));
            map.put("invoice", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getInvoice()));
            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "项目销售记录.xlsx";
        }
        String templateName = "项目销售记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }

    @Log(title = "全部销售信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportSaleAll")
    public AjaxResult exportSaleAll(GoodsSale entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        startPage();
        List<GoodsSale> list = goodsSaleService.selectList(entity);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            // map.put("parentDept", e.getReturnDept().getParentName());
            map.put("saleDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getSaleDate()));
            map.put("invoice", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getInvoice()));
            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "销售记录.xlsx";
        }
        String templateName = "全部销售记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }
    /**
     * 获取销售信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsSaleService.selectById(id));
    }

    /**
     * 获取销售信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:query')")
    @GetMapping(value = "/storeReject/{id}")
    public AjaxResult storeReject(@PathVariable("id") String id) {
        GoodsSale goodsSale = goodsSaleService.selectById(id);
        goodsSale.setStatus(BusinessConstants.GOODS_30);
        return AjaxResult.success(goodsSaleService.update(goodsSale));
    }



    //删除产品
    @Log(title = "非退回产品的删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteByIdThree/{id}")
    public AjaxResult deleteByIdThree(@PathVariable("id") String id) {
        goodsSaledoService.deleteByGoodsSaleId(id);
        return toAjax(  goodsSaleService.deleteByIdThree(id) );
    }

    //新增产品提交到二次请购
    @Log(title = "新增产品提交到二次请购", businessType = BusinessType.DELETE)
    @DeleteMapping("/toAgain/{id}")
    public AjaxResult toAgain(@PathVariable("id") String id) {
        GoodsSale goodsSale = goodsSaleService.selectById(id);
        goodsSale.setStatus(BusinessConstants.GOODS_31);
        goodsSale.setLockCount(BigDecimal.ZERO);
        goodsSale.setPleaseBuyCount(BigDecimal.ZERO);
        return toAjax(  goodsSaleService.update(goodsSale) );
    }
    //关闭产品
    @Log(title = "退回产品的删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteByIdFour/{id}")
    public AjaxResult deleteByIdFour(@PathVariable("id") String id) {
        goodsSaledoService.deleteByGoodsSaleId(id);
        GoodsSale goodsSale=goodsSaleService.selectById(id);
        goodsSale.setDelFlag("4");
        goodsSale.setStatus(BusinessConstants.SALE_TYPE_29);
        goodsSale.setIsclose("1");
        goodsSale.setModifyuser(getNickname());
        goodsSale.setModifyremark("关闭退回产品");
        // 如果有锁定数量 则退回
        if (goodsSale.getLockCount().compareTo(BigDecimal.ZERO)>0){
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goodsSale.getLockCount()));
            goodsOrderInService.update(goodsOrderIn);
            goodsSale.setLockCount(BigDecimal.ZERO);
        }
        goodsSaleService.update(goodsSale);
        return success();
        //return toAjax(  goodsSaleService.deleteByIdFour(id) );
    }

    //关闭销售订单产品
    @Log(title = "关闭销售订单产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteSaleFour/{id}")
    public AjaxResult deleteSaleFour(@PathVariable("id") String id) {
        GoodsSale goodsSale=goodsSaleService.selectById(id);
        //goodsSale.setDelFlag("2");
        goodsSale.setStatus(BusinessConstants.SALE_TYPE_29);
        goodsSale.setIsclose("1");
        goodsSale.setModifyuser(getNickname());
        goodsSale.setModifyremark("关闭销售订单产品");
        // 如果有锁定数量 则退回
        if (goodsSale.getLockCount().compareTo(BigDecimal.ZERO)>0){
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goodsSale.getLockCount()));
            goodsOrderInService.update(goodsOrderIn);
            goodsSale.setLockCount(BigDecimal.ZERO);
        }
        goodsSaleService.update(goodsSale);
        ProjectBaseInfo projectBaseInfo=projectBaseInfoService.selectById(goodsSale.getProjectId());
        projectBaseInfo.setContractMoney(projectBaseInfo.getContractMoney().subtract(goodsSale.getGoodsTaxTotalPrice()));
        projectBaseInfoService.update(projectBaseInfo);
        return success();
    }

    @GetMapping("/listIds/{ids}")
    public AjaxResult listIds(@PathVariable("ids")  String[] ids) {
        GoodsInvoice goodsInvoice = new GoodsInvoice();
        Map<String,Object> stringMap= new HashMap<>();
        List<GoodsSale> list = Lists.newArrayList();
        List<String> customerList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(ids)){
            for(String id : ids){
                GoodsSale gs = goodsSaleService.selectById(id);
                list.add(gs);
                if(!customerList.contains(gs.getCustomerId())){
                    customerList.add(gs.getCustomerId());
                }
                if(BusinessConstants.STATUS_YES.equals(gs.getInvoice())){
                    //list = Lists.newArrayList();
                    //return getDataTable(list);
                    return error("您选择销售数据中部分已经开具发票，请重新选择！");
                }
            }
        }
        if(customerList.size() > 1){
//            list = Lists.newArrayList();
//            return getDataTable(list);
            return error("您选择销售数据中存在多个客户，请重新选择！");
        }
        BigDecimal total = BigDecimal.ZERO;
        for(GoodsSale gs : list){
            BigDecimal goodsTotalPrice = gs.getGoodsTotalPrice();
            total = total.add(goodsTotalPrice);
        }
        return success();
        //return getDataTable(list);
    }

    /**
     * 新增销售信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:add')")
    @Log(title = "销售信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsSale entity) {
        return toAjax(goodsSaleService.insert(entity));
    }

    /**
     * 非订单产品的新增
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:add')")
    @Log(title = "自制非订单产品的新增", businessType = BusinessType.INSERT)
    @PostMapping("/addNotProject")
    public AjaxResult addNotProject(@RequestBody GoodsSale entity) {
        return toAjax(goodsSaleService.addNotProject(entity));
    }

    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody GoodsSale entity) {
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(entity.getGoodsId());
        goodsOrderIn.setCount(goodsOrderIn.getCount().add(entity.getGoodsCount()));
        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(entity.getGoodsCount()));
        goodsOrderInService.update(goodsOrderIn);
        return toAjax(goodsSaleService.insert(entity));
    }

    @PutMapping("/editOrder")
    public AjaxResult editOrder(@RequestBody GoodsSale entity) {
        GoodsSale goodsSale=goodsSaleService.selectById(entity.getId());
        GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(entity.getGoodsId());
        goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(goodsSale.getGoodsCount()).add(entity.getGoodsCount()));
        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(goodsSale.getGoodsCount()).add(entity.getGoodsCount()));
        goodsOrderInService.update(goodsOrderIn);
        entity.setFahuoShengyu(entity.getOrderCount());
        return toAjax(goodsSaleService.update(entity));
    }
    /*@Log(title = "销售信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/addForSale")
    public AjaxResult addForSale(@RequestBody GoodsSale entity) {
        return toAjax(goodsSaleService.insertForSale(entity));
    }*/

    /*@PutMapping
    public AjaxResult addBatch(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertBatch(entity);
        return AjaxResult.success("销售成功");
    }*/

    @PostMapping("/insertBatch")
    public AjaxResult insertBatch(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertBatch(entity);
        return AjaxResult.success("销售成功");
    }

    @GetMapping("/listSaleProject")
    public TableDataInfo listSaleProject(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listByProjectId(entity);
        return getDataTable(list);
    }

    @GetMapping("/listSaleLvdo")
    public TableDataInfo listSaleLvdo(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listByProjectId(entity);
        return getDataTable(list);
    }
    @GetMapping("/selectListNotProject")
    public TableDataInfo selectListNotProject(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.selectListNotProject(entity);
        return getDataTable(list);
    }
    /*@PutMapping("/insert")
    public AjaxResult insertSale(@Validated @RequestBody GoodsSale entity) {
        *//*for(String id:entity.getIds().split(",")){
            GoodsOrderIn goodsOrderIn=goodsOrderInService.selectById(id);
            if(goodsOrderIn!=null){
                GoodsSale goodsSale=new GoodsSale();
                goodsSale.setProjectId(entity.getProjectId());
                goodsSale.setType(BusinessConstants.TYPE_PROJECT);
                goodsSale.setGoodsId(goodsOrderIn.getId());
                goodsSale.setGoodsName(goodsOrderIn.getName());
                goodsSale.setGoodsBrand(goodsOrderIn.getBrand());
                goodsSale.setGoodsUnitPrice(goodsOrderIn.getCostPrice());
                goodsSale.setGoodsCount(goodsOrderIn.getGoodsTotalPrice().intValue());
                goodsSale.setGoodsTotalPrice(goodsOrderIn.getCostPrice().multiply(goodsOrderIn.getGoodsTotalPrice()));
                goodsSale.setSaleDate(new Date());
                goodsSale.setSupplierId(goodsOrderIn.getSupplierId());
                goodsSale.setSupplierName(goodsOrderIn.getSupplierName());
                //goodsSale.setCustomerId(goodsOrderIn.getCus());
                goodsSale.setSaleId(getUserId());
                goodsSale.setSaleName(getUsername());
                goodsSaleService.insert(goodsSale);
            }
        }*//*
        for(GoodsOrderIn goodsOrderIn:entity.getColumns()){
            GoodsSale goodsSale=new GoodsSale();
            goodsSale.setProjectId(entity.getProjectId());
            goodsSale.setType(BusinessConstants.TYPE_PROJECT);
            goodsSale.setGoodsId(goodsOrderIn.getId());
            goodsSale.setGoodsName(goodsOrderIn.getName());
            goodsSale.setGoodsBrand(goodsOrderIn.getBrand());
            goodsSale.setGoodsUnitPrice(goodsOrderIn.getGoodsUnitPrice());
            goodsSale.setGoodsCount(goodsOrderIn.getGoodsCount().intValue());
            goodsSale.setGoodsTotalPrice(goodsOrderIn.getGoodsUnitPrice().multiply(BigDecimal.valueOf(goodsOrderIn.getGoodsCount())));
            goodsSale.setSaleDate(new Date());
            goodsSale.setSupplierId(goodsOrderIn.getSupplierId());
            goodsSale.setSupplierName(goodsOrderIn.getSupplierName());
            //goodsSale.setCustomerId(goodsOrderIn.getCus());
            goodsSale.setSaleId(getUserId());
            goodsSale.setSaleName(getUsername());
            goodsSaleService.insert(goodsSale);

            goodsOrderIn.setRemainderCount( goodsOrderIn.getRemainderCount()-goodsSale.getGoodsCount());
            goodsOrderInService.update(goodsOrderIn);
        }
        return AjaxResult.success("选择完成！");
    }*/
    //订单产品请假添加
    @PostMapping("/insertForPrj")
    public AjaxResult insertForPrj(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertBatch(entity);
//        goodsSaleService.insertForPrj(entity);

        return AjaxResult.success("选择完成！");
    }
    @PostMapping("/insertForPrjNew")
    public AjaxResult insertForPrjNew(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertForPrjNew(entity);
        return AjaxResult.success("选择完成！");
    }
    @PostMapping("/insertForPrjGygx")
    public AjaxResult insertForPrjGygx(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertForPrjGygx(entity);
        return AjaxResult.success("选择完成！");
    }

    @PostMapping("/insertForPrjGygxAll")
    public AjaxResult insertForPrjGygxAll(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertForPrjGygxAll(entity);
        return AjaxResult.success("选择完成！");
    }
    //订单添加其他产品或者配件辅件购买
    @PostMapping("/insertForPrjDo")
    public AjaxResult insertForPrjDo(@Validated @RequestBody GoodsSaledo entity) {
        goodsSaledoService.insertBatchDo(entity);
        return AjaxResult.success("选择完成！");
    }



    //添加订单产品到 请购列表
    @PostMapping("/insertFromGoodsSale")
    public AjaxResult insertFromGoodsSale(@Validated @RequestBody GoodsSaledo entity) {
        goodsSaledoService.insertFromGoodsSale(entity);
        return AjaxResult.success("选择完成！");
    }



    //铁件产品添加
    @PostMapping("/insertPleaseBuyForIron")
    public AjaxResult insertPleaseBuyForIron(@Validated @RequestBody GoodsSaledo entity) {
        goodsSaledoService.insertPleaseBuyForIron(entity);
        return AjaxResult.success("选择完成！");
    }

    /**
     * 修改销售信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:edit')")
    @Log(title = "销售信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsSale entity) {
//        entity.setFahuoShengyu(entity.getOrderCount());
        if(StringUtils.isNotBlank(entity.getInnerGoodsId())){
            GoodsOrderInner goodsOrderInner = goodsOrderInnerService.selectById(entity.getInnerGoodsId());
            entity.setInnerGoodsId(goodsOrderInner.getId());
            entity.setInnerGoodsCode(goodsOrderInner.getCode());
            entity.setInnerGoodsName(goodsOrderInner.getName());
        }
        return toAjax(goodsSaleService.update(entity));
    }

    @PutMapping("/editRemark")
    public AjaxResult editRemark(@RequestBody GoodsSale entity) {
//        entity.setFahuoShengyu(entity.getOrderCount());
        return toAjax(goodsSaleService.editRemark(entity));
    }

    @PostMapping("/addAgain")
    public AjaxResult addAgain(@RequestBody GoodsSale entity) {
        return toAjax(goodsSaleService.addAgain(entity));
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:edit')")
    @Log(title = "退回产品变更", businessType = BusinessType.UPDATE)
    @PutMapping("/editAgain")
    public AjaxResult editAgain(@RequestBody GoodsSale entity) {
        return toAjax(goodsSaleService.editAgain(entity));
    }
    /**
     * 删除销售信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSale:remove')")
    @Log(title = "销售信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(goodsSaleService.deleteByIds(ids));
    }

    @Log(title = "删除并修改库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteAndModidyOrderin/{ids}")
    public AjaxResult deleteAndModidyOrderin(@PathVariable String[] ids) {
        for(String id:ids){
            GoodsSale goodsSale=goodsSaleService.selectById(id);
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goodsSale.getGoodsCount()));
            goodsOrderIn.setShengyu(goodsOrderIn.getRemainderCount().multiply(goodsOrderIn.getCostPriceTax()));
            goodsOrderInService.update(goodsOrderIn);

            SysArea sysArea=areaService.selectAreaById(goodsOrderIn.getDeptId());
            sysArea.setShengyu(sysArea.getShengyu().add(goodsOrderIn.getRemainderCount()));
            sysArea.setAllmaoney(sysArea.getAllmaoney().add(goodsOrderIn.getShengyu()));
            areaService.updateArea(sysArea);
        }
        return toAjax(goodsSaleService.deleteByIds(ids));
    }

    @Log(title = "删除订单产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteById/{ids}")
    public AjaxResult deleteById(@PathVariable String[] ids) {
        // 订单合同金额 减去 对应金额
        for(String saleId:ids){
            GoodsSale goodsSale = goodsSaleService.selectById(saleId);
            ProjectBaseInfo order = projectBaseInfoService.selectById(goodsSale.getProjectId());
            order.setContractMoney(order.getContractMoney().subtract(goodsSale.getGoodsTaxTotalPrice()));
            projectBaseInfoService.update(order);
        }
        return toAjax(goodsSaleService.deleteByIds(ids));
    }

    @Log(title = "删除并修改库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteOrderin/{ids}")
    public AjaxResult deleteOrderin(@PathVariable String[] ids) {
        for(String id:ids){
            GoodsSale goodsSale=goodsSaleService.selectById(id);
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
            goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(goodsSale.getGoodsCount()));
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(goodsSale.getGoodsCount()));
            goodsOrderIn.setShengyu(goodsOrderIn.getRemainderCount().multiply(goodsOrderIn.getCostPriceTax()));
            goodsOrderInService.update(goodsOrderIn);

            SysArea sysArea=areaService.selectAreaById(goodsOrderIn.getDeptId());
            sysArea.setShengyu(sysArea.getShengyu().add(goodsOrderIn.getRemainderCount()));
            sysArea.setAllmaoney(sysArea.getAllmaoney().add(goodsOrderIn.getShengyu()));
            areaService.updateArea(sysArea);
        }
        return toAjax(goodsSaleService.deleteByIds(ids));
    }

    @Log(title = "删除项目商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteProject/{ids}")
    public AjaxResult deleteProject(@PathVariable String[] ids) {
        /*for(String id:ids){
            GoodsSale goodsSale=goodsSaleService.selectById(ids[0]);
            GoodsOrderIn goodsOrderIn = goodsOrderInService.selectById(goodsSale.getGoodsId());
            if (goodsOrderIn != null) {
               // if(goodsSale.getStatus().equals(BusinessConstants.STATUS_YES)) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount() + goodsSale.getGoodsCount());
                    goodsOrderInService.update(goodsOrderIn);
               // }
            }
        }*/
        return toAjax(goodsSaleService.deletSaleInfoForPrj(ids[0]));
    }

    @Log(title = "订单信息导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(GoodsSale entity, MultipartFile file) {
        String projectId  = entity.getProjectId();
        if(StringUtils.isBlank(projectId)){
            return AjaxResult.error("请选择订单");
        }else{
            projectId = projectId.replace("?updateSupport=0","");
        }
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(projectId);
        Map<String, Object> error = new HashMap<>();
        error = goodsSaleService.importData(entity,file,projectBaseInfo);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    //订单的产品生产入库（之前的按订单来的）
    @PostMapping("/insertRuku")
    public AjaxResult insertRuku(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertRuku(entity);
        return AjaxResult.success("选择完成！");
    }

    //自制生产提交到质检
    @PostMapping("/insertRukuToZhijian")
    public AjaxResult insertRukuToZhijian(@Validated @RequestBody GoodsSale entity) {
        goodsSaleService.insertRukuToZhijian(entity);
        return AjaxResult.success("选择完成！");
    }

    @GetMapping("/listByOrderIds")
    public TableDataInfo listByOrderIds(GoodsSale entity) {
        Map<String,Object> params = new HashMap<>();
        params.put("ids",entity.getIds().split(","));
        entity.setParams(params);
        List<GoodsSale> list = goodsSaleService.listByOrderIds(entity);
        for (GoodsSale goodsSale: list) {
            // 如果订单数量大于可用数量
            if (goodsSale.getOrderCount().compareTo(goodsSale.getRemainderCount()) >= 0) {
                goodsSale.setPleaseBuyCount(goodsSale.getOrderCount().subtract(goodsSale.getRemainderCount()));
                goodsSale.setLockCount(goodsSale.getRemainderCount());
            }else{
                goodsSale.setPleaseBuyCount(BigDecimal.ZERO);
                goodsSale.setLockCount(goodsSale.getOrderCount());
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/listMergeByOrders")
    public TableDataInfo listMergeByOrders(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listMergeByOrders(entity);
        return getDataTable(list);
    }

    @GetMapping("/listNoMergeByOrders")
    public TableDataInfo listNoMergeByOrders(GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleService.listNoMergeByOrders(entity);
        return getDataTable(list);
    }

    /**
     * 导出多个订单产品汇总列表 合并产品
     */
    @Log(title = "导出订单产品列表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportMergeDataByOrders")
    public void exportMergeDataByOrders(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        goodsSaleService.exportMergeDataByOrders(request,response,entity);
    }

    /**
     * 导出多个订单产品汇总列表  不合并产品
     */
    @Log(title = "导出订单产品列表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportNoMergeDataByOrders")
    public void exportNoMergeDataByOrders(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        goodsSaleService.exportNoMergeDataByOrders(request,response,entity);
    }


}
